import { type EditGroupParams, editGroup, type AddGroupParams, addGroup, type GroupItemsParams, type DeleteMemberParams, deleteMember, excelImport, txtImport } from './apis';
import { VcMessage } from 'vc';
import * as XLSX from 'xlsx';

export function useEditNameDialog() {
  const editGroupName = ref('');

  const recommendItems = ['我关注的企业', '我关注的供应商', '我的贷款企业'];

  const handleEditNameDialogOpen = (groupName: string) => {
    editGroupName.value = groupName;
  };

  const setGroupName = (name: string) => {
    editGroupName.value = name;
  };

  const handleEditNameDialogConfirm = async (groupId: number, emit: any, ref: any) => {
    const params: EditGroupParams = {
      name: editGroupName.value
    };
    const res = await editGroup(groupId, params);
    if (res.code === 200) {
      emit('change');
      VcMessage.success('修改成功');
      try {
        ref?.closeFn();
      } catch {}
    } else {
      VcMessage.error('修改失败');
    }
  };

  return {
    editGroupName,
    recommendItems,
    handleEditNameDialogOpen,
    setGroupName,
    handleEditNameDialogConfirm
  };
}

export function useAddGroupDialog() {
  const addGroupName = ref('');

  const recommendItems = ['我关注的企业', '我关注的供应商', '我的贷款企业'];

  const setGroupName = (name: string) => {
    addGroupName.value = name;
  };

  const handleAddGroupDialogOpen = () => {
    addGroupName.value = '';
  };

  const handleAddGroupDialogConfirm = async (emit: any, ref: any) => {
    if (!addGroupName.value) {
      VcMessage.warning('组合名称不能为空');
      return;
    }
    const params: AddGroupParams = {
      name: addGroupName.value
    };
    const res = await addGroup(params);
    if (res.code === 200) {
      emit('addGroup');
      VcMessage.success('新建组合成功');
      try {
        ref?.closeFn();
      } catch {}
    } else {
      VcMessage.error('新建失败');
    }
  };

  return {
    addGroupName,
    recommendItems,
    setGroupName,
    handleAddGroupDialogOpen,
    handleAddGroupDialogConfirm
  };
}

export function useMemberManageDialog() {
  const contentKey = ref(0);

  const searchComapnyTxt = ref('');

  const memberDeleteDialog = ref(false);

  const memberCheckedList = ref([]);

  const handleBatchDelete = (tableRef: any) => {
    try {
      memberCheckedList.value = tableRef?.VcTable?.getCheckboxRecords() || [];
      if (!memberCheckedList.value.length) {
        VcMessage.warning('请选择需要删除的成员');
      } else {
        memberDeleteDialog.value = true;
      }
    } catch {}
  };

  const handleMemberDelete = async (groupId: number, ref: any, cb: Function) => {
    const params: DeleteMemberParams = {
      groupId,
      ids: memberCheckedList.value.map((item: any) => item.id).join(',')
    };
    const res = await deleteMember(params);
    if (res.code === 200) {
      VcMessage.success('删除成功');
      try {
        ref?.close();
        cb(groupId, true);
      } catch {}
    } else {
      VcMessage.error('删除失败');
    }
  };

  const searchMemberTxt = ref('');

  const memberHandlerInput = (queryData: GroupItemsParams) => {
    queryData.searchTxt = searchMemberTxt.value;
  };

  return {
    contentKey,
    searchComapnyTxt,
    memberDeleteDialog,
    memberCheckedList,
    handleBatchDelete,
    handleMemberDelete,
    searchMemberTxt,
    memberHandlerInput
  };
}

export function useBatchImportDialog() {
  const loading = ref(false);

  const handleFileChange = async (file: any, fileList: any, emit: any) => {
    const fileType = ['xlsx', 'xls'].some((item) => item === file.name.split('.')[1]);
    if (!fileType) {
      VcMessage.error('文件格式错误，请重新选择！');
      return;
    }
    loading.value = true;
    let formData = new FormData();
    formData.append('file', file.raw);
    const res = await excelImport(formData);
    loading.value = false;
    if (res.code === 200) {
      emit('success', res.data);
    } else {
      VcMessage.error(res.msg);
    }
    // else if (res.code === 409011 || res.code === 409012) {
    //   VcMessage.error(res.msg);
    // } else {
    //   VcMessage.error('导入失败，请重新导入');
    // }
  };

  const downloadFileTemplate = () => {
    const tabValues = [['中国石油天然气股份有限公司'], ['安徽海螺水泥股份有限公司'], ['比亚迪股份有限公司']];
    const fileName = '下载模板.xlsx';
    const wb = XLSX.utils.book_new();
    const ws = XLSX.utils.aoa_to_sheet(tabValues);
    XLSX.utils.book_append_sheet(wb, ws, 'SheetJS');
    XLSX.writeFile(wb, fileName);
  };

  const showExampleImage = ref(false);
  const toggleExampleImageShow = (show: boolean) => {
    showExampleImage.value = show;
  };

  const importTxt = ref('');

  const clearImportTxt = () => {
    importTxt.value = '';
  };

  const handleTxtImport = async (emit: any) => {
    const txtArr = importTxt.value.split('\n');
    loading.value = true;
    const res = await txtImport(txtArr);
    loading.value = false;
    if (res.code === 200) {
      emit('success', res.data);
    } else {
      VcMessage.error(res.msg);
    }
    // else if (res.code === 400) {
    //   VcMessage.error(res.msg);
    // } else {
    //   VcMessage.error('导入失败，请重新导入');
    // }
  };

  return {
    loading,
    handleFileChange,
    downloadFileTemplate,
    showExampleImage,
    toggleExampleImageShow,
    importTxt,
    clearImportTxt,
    handleTxtImport
  };
}
